<template>
  <Dialog v-model="dialogVisible" title="购买产品" width="600" :before-close="handleClose">
    <el-form
      v-show="orderType == 0"
      ref="ruleFormRef"
      :model="bizForm"
      :rules="rules"
      label-width="auto"
      class="demo-ruleForm"
      :size="formSize"
      status-icon
    >
      <el-form-item label="产品名称：">
        {{ bizForm.bizName }}
      </el-form-item>
      <el-form-item label="产品单价：">
        ￥<el-text type="danger">{{ bizForm.bizPrice }}/{{ bizForm.bizUnit }}</el-text>
      </el-form-item>
      <el-form-item label="购买数量：" prop="bizNum">
        <el-input
          v-if="showMore"
          v-model.number="bizForm.bizNum"
          type="number"
          clearable
          :maxlength="maxLength"
          @input="filterNonPositiveIntegers"
        ></el-input>
        <el-radio-group v-else @change="filterNonPositiveIntegers" v-model="bizForm.bizNum">
          <el-radio-button
            v-for="(item, index) in numSelectOptions[bizForm.bizType]"
            :key="'s' + index"
            :label="item.value"
            >{{ item.text }}</el-radio-button
          >
          <el-radio-button @click="showMore = true">其他</el-radio-button>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="总价:">
        ￥<el-text type="danger">{{ bizForm.totalPrice.toLocaleString('en-US') }}</el-text>
      </el-form-item>
      <div style="display: flex; justify-content: flex-end">
        <el-button @click="resetForm(ruleFormRef)">取消</el-button>
        <el-button type="primary" @click="submitForm(ruleFormRef)"> 创建订单 </el-button>
      </div>
    </el-form>
    <!-- 支付方式支付 -->
    <Pay v-if="orderType == 1" @set-order-map="setOrderMap" :value="bizForm" />
    <!-- 支付后订单状态的状态 -->
    <orderStatus
      v-if="orderType == 2"
      @set-order-map="setOrderMap"
      @handle-close="handleClose"
      @refresh-parent-data="refreshParentData"
    />
  </Dialog>
</template>

<script setup lang="ts">
const dialogVisible = ref(false)
import { byTypeBiz, createPay } from '@/api/Profile/system'
import Pay from './pay.vue'
import orderStatus from './orderStatus.vue'

const maxLength = ref(4)
const emit = defineEmits(['initData'])

const showMore = ref(false)

interface RuleForm {
  bizName: string
  bizPrice: Number
  bizNum: Number
  bizType: string
  totalPrice: Number
  orderId: String
  appId: Number
  bizUnit: String
}
// 订单进行状态  0-创建订单状态 1选择支付状态 2订单是否完成支付
const orderType = ref(0)

const setOrderMap = (val) => {
  orderType.value = val
}

// 刷新父级数据
const refreshParentData = () => {
  emit('initData')
}

const numSelectOptions = {
  1: [
    { text: '1个', value: 1 },
    { text: '5个', value: 5 },
    { text: '10个', value: 10 },
    { text: '20个', value: 20 }
  ],
  2: [
    { text: '100分钟', value: 100 },
    { text: '500分钟', value: 500 },
    { text: '2000分钟', value: 2000 },
    { text: '5000分钟', value: 5000 }
  ],
  3: [
    { text: '1个', value: 1 },
    { text: '5个', value: 5 },
    { text: '10个', value: 10 },
    { text: '20个', value: 20 }
  ],
  4: [
    { text: '100分钟', value: 100 },
    { text: '500分钟', value: 500 },
    { text: '2000分钟', value: 2000 },
    { text: '5000分钟', value: 5000 }
  ],
  5: [
    { text: '1个', value: 1 },
    { text: '5个', value: 5 },
    { text: '10个', value: 10 },
    { text: '20个', value: 20 }
  ]
}

const formSize = ref('default')
const ruleFormRef = ref<FormInstance>()
const bizForm = reactive<RuleForm>({
  bizName: '',
  bizPrice: 0,
  bizNum: 0,
  bizType: 1,
  totalPrice: 0,
  orderId: 0,
  bizUnit: '',
  appId: 1
})
const rules = reactive<FormRules<RuleForm>>({
  bizNum: [
    { required: true, message: '请输入产品数量', trigger: 'blur' },
    { pattern: /^[1-9]\d*$/, message: '请输入大于0的整数', trigger: 'blur' }
  ]
})
// 创建订单
const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate(async (valid, fields) => {
    if (valid) {
      const orderId = await createPay({ ...bizForm })
      if (orderId) {
        bizForm.orderId = orderId
        orderType.value = 1
      }
    } else {
    }
  })
}
// 取消
const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.resetFields()
  dialogVisible.value = false
}

// 处理数据
const filterNonPositiveIntegers = (value) => {
  // 当输入超过最大长度时，截取到最大长度并提示用户
  if (value.length > maxLength.value) {
    bizForm.bizNum = value.substring(0, maxLength.value)
    bizForm.totalPrice = (bizForm.bizNum * (bizForm.bizPrice * 100)) / 100
    ElMessage.warning(`输入已超过最大长度限制为 ${maxLength.value}!`)
  }
  // 过滤非正整数
  else if (!/^\d*$/.test(bizForm.bizNum)) {
    bizForm.bizNum = 0
    bizForm.totalPrice = 0
  } else {
    // 是正整数，更新数据
    bizForm.bizNum = parseInt(bizForm.bizNum)
    if (isNaN(bizForm.bizNum)) {
      bizForm.totalPrice = 0
    } else {
      bizForm.totalPrice = (bizForm.bizNum * (bizForm.bizPrice * 100)) / 100
    }
  }
}

// 显示
const showDialog = async (type) => {
  orderType.value = 0
  bizForm.totalPrice = 0
  bizForm.bizNum = 0
  dialogVisible.value = true
  showMore.value = false
  getProudctDetail(type)
}
// 获取产品详情
const getProudctDetail = async (type) => {
  const { bizName, bizPrice, bizType, bizUnit } = await byTypeBiz(type)
  bizForm.bizName = bizName
  bizForm.bizPrice = bizPrice
  bizForm.bizType = bizType
  bizForm.bizUnit = bizUnit
}

const handleClose = () => {
  dialogVisible.value = false
}
defineExpose({ showDialog })
</script>

<style lang="scss" scoped></style>
@/api/Profile/account
